﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPinyin;

namespace AreaHelper
{
    /// <summary>
    /// 拼音转换类
    /// </summary>
    internal class PinYin
    {

        /// <summary>
        /// 简拼转换
        /// </summary>
        /// <param name="character"></param>
        /// <returns></returns>
        public static string ConvertAbb(string character)
        {

            //易错拼音地名则单独取词库的正确拼音
            //完整匹配易错拼音地名，直接取词库正确拼音
            var place = PlacePY.PlaceDict.SingleOrDefault(c => c.Key.CompareTo(character) == 0);
            if (place.Key != null)
            {
                string py = "";
                var pyArr = place.Value.Split(' ');
                foreach (string s in pyArr)
                {
                    py += s.Substring(0, 1);
                }
                return py.ToUpper();
            }

            //将县、市、区截取,匹配易错拼音地名
            var placeStr = character.Replace("县", "").Replace("市", "").Replace("区", "");
            place = PlacePY.PlaceDict.SingleOrDefault(c => c.Key.CompareTo(placeStr) == 0);
            if (place.Key != null)
            {
                string areaType = character.Split(new string[] { place.Key }, StringSplitOptions.RemoveEmptyEntries)[0];
                string py = "";
                var pyArr = place.Value.Split(' ');
                foreach (string s in pyArr)
                {
                    py += s.Substring(0, 1);
                }
                return (py + Pinyin.GetInitials(areaType)).Replace(" ", "").ToUpper();
            }

            string pinyin = Pinyin.GetInitials(character);
            return pinyin.ToUpper();

        }

        /// <summary>
        /// 全拼转换
        /// </summary>
        /// <param name="character"></param>
        /// <returns></returns>
        public static string ConvertFull(string character)
        {

            //易错拼音地名则单独取词库的正确拼音
            //完整匹配易错拼音地名，直接取词库正确拼音
            var place = PlacePY.PlaceDict.SingleOrDefault(c => c.Key.CompareTo(character) == 0);

            if (place.Key != null)
            {
                return place.Value.Replace(" ", "");
            }

            //将县、市、区截取,匹配易错拼音地名
            var placeStr = character.Replace("县", "").Replace("市", "").Replace("区", "");
            place = PlacePY.PlaceDict.SingleOrDefault(c => c.Key.CompareTo(placeStr) == 0);
            if (place.Key != null)
            {
                var areaType = character.Split(new string[] { place.Key }, StringSplitOptions.RemoveEmptyEntries)[0];
                return (place.Value + Pinyin.GetPinyin(areaType)).Replace(" ", "");
            }
            string pinyin = Pinyin.GetPinyin(character).Replace(" ", "");
            return pinyin;

        }
    }
}
